﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Model
{
    public class MessageService
    {
        public ServiceResult<List<MessageClip>> GetMessageClipList(int userId, int page, int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                MessageClipRepository reps = new MessageClipRepository(dbContext);

                List<MessageClip> lst = reps.GetList(userId, page, limit);

                return new ServiceResult<List<MessageClip>>(ErrorCode.NoError, lst);
            }
        }

        public ServiceResult<List<Data.MessageClipView>> GetMessageClipListByType(int userId, int type, int start, int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                MessageClipRepository reps = new MessageClipRepository(dbContext);

                List<Data.MessageClipView> lst = reps.GetListByType(userId, type, start, limit);

                return new ServiceResult<List<Data.MessageClipView>>(ErrorCode.NoError, lst);
            }
        }

        public ServiceResult<Data.NewMessageCount> GetNewMessageCount(int userId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                MessageClipRepository reps = new MessageClipRepository(dbContext);

                return new ServiceResult<Data.NewMessageCount>(ErrorCode.NoError, reps.GetNewMessageCount(userId));
            }
        }

        /// <summary>
        /// 获取消息夹里最新的消息
        /// </summary>
        /// <param name="messageClipId"></param>
        /// <returns></returns>
        public ServiceResult<Data.MessageView> GetLatestMessage4Clip(Guid messageClipId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                MessageRepository reps = new MessageRepository(dbContext);
                return new ServiceResult<Data.MessageView>(ErrorCode.NoError, reps.GetList(messageClipId).FirstOrDefault());
            }
        }

        public ServiceResult<Message> SendToUser(int userId, int targetUserId, string content)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                DateTime now = DateTime.Now;
                string selfClipIdentityText = string.Format("{0}-{1}", targetUserId, userId);
                string targetClipIdentityText = string.Format("{0}-{1}", userId, targetUserId);
                MessageRepository reps = new MessageRepository(dbContext);
                MessageClipRepository mcReps = new MessageClipRepository(dbContext);

                #region 为自己创建消息
                // 获取目标消息夹
                MessageClip selfClip = mcReps.Get(BasicData.MessageClipType.FriendsNotice, selfClipIdentityText);
                if (selfClip == null)
                {
                    selfClip = new MessageClip();
                    selfClip.Id = Guid.NewGuid();
                    selfClip.CreatedTime = now;
                    selfClip.ReceiverId = userId;
                    selfClip.MessageCount = 1;
                    selfClip.NewMessageCount = 1;
                    selfClip.LastestContent = content;
                    selfClip.LastestSenderId = userId;
                    selfClip.LastestTitle = "消息";
                    selfClip.LastestUpdatedTime = now;

                    selfClip.Type = BasicData.MessageClipType.FriendsNotice;
                    selfClip.MessageType = BasicData.MessageType.PersonalInstantMessage;
                    selfClip.IdentityText = selfClipIdentityText;

                    selfClip.Tag = targetUserId.ToString();

                    mcReps.Create(selfClip);
                }
                else
                {
                    selfClip.MessageCount++;
                    selfClip.LastestContent = content;
                    selfClip.LastestSenderId = userId;
                    selfClip.LastestTitle = "消息";
                    selfClip.LastestUpdatedTime = now;
                    selfClip.IsDeleted = false;
                    mcReps.Update(selfClip);
                }
                // 创建消息
                Message selfMessage = new Message();
                selfMessage.Id = Guid.NewGuid();
                selfMessage.SenderId = userId;
                selfMessage.ReceiverId = targetUserId;
                selfMessage.Content = content;
                selfMessage.CreatedTime = DateTime.Now;
                selfMessage.Type = BasicData.MessageType.PersonalInstantMessage;
                selfMessage.MessageClipId = selfClip.Id;
                reps.Create(selfMessage);
                #endregion

                #region 为对方创建消息
                // 获取目标消息夹
                MessageClip targetClip = mcReps.Get(BasicData.MessageClipType.FriendsNotice, targetClipIdentityText);
                if (targetClip == null)
                {
                    targetClip = new MessageClip();
                    targetClip.Id = Guid.NewGuid();
                    targetClip.CreatedTime = now;
                    targetClip.ReceiverId = targetUserId;
                    targetClip.MessageCount = 1;
                    targetClip.NewMessageCount = 1;
                    targetClip.LastestContent = content;
                    targetClip.LastestSenderId = userId;
                    targetClip.LastestTitle = "消息";
                    targetClip.LastestUpdatedTime = now;

                    targetClip.Type = BasicData.MessageClipType.FriendsNotice;
                    targetClip.MessageType = BasicData.MessageType.PersonalInstantMessage;
                    targetClip.IdentityText = targetClipIdentityText;

                    targetClip.Tag = userId.ToString();

                    mcReps.Create(targetClip);
                }
                else
                {
                    targetClip.MessageCount++;
                    targetClip.NewMessageCount++;
                    targetClip.LastestContent = content;
                    targetClip.LastestSenderId = userId;
                    targetClip.LastestTitle = "消息";
                    targetClip.LastestUpdatedTime = now;
                    targetClip.IsDeleted = false;
                    mcReps.Update(targetClip);
                }
                // 创建消息
                Message targetMessage = new Message();
                targetMessage.Id = Guid.NewGuid();
                targetMessage.SenderId = userId;
                targetMessage.ReceiverId = targetUserId;
                targetMessage.Content = content;
                targetMessage.CreatedTime = DateTime.Now;
                targetMessage.Type = BasicData.MessageType.PersonalInstantMessage;
                targetMessage.MessageClipId = targetClip.Id;
                reps.Create(targetMessage);
                #endregion

                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<Message>(ErrorCode.NoError, targetMessage);
                }
                return new ServiceResult<Message>(ErrorCode.DB_Error);
            }
        }

        public ServiceResult<string> SendToActivity(int userId, Guid activityId, string content)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository aRep = new ActivityRepository(dbContext);
                ActivityMemberRepository amRep = new ActivityMemberRepository(dbContext);
                MessageRepository reps = new MessageRepository(dbContext);
                MessageClipRepository mcReps = new MessageClipRepository(dbContext);

                Activity activity = aRep.Get(activityId);
                ActivityMember member = amRep.Get(activityId, userId);

                if (member == null && activity.CreatorId != userId)
                {
                    // 不是队长,切没加入活动
                    return new ServiceResult<string>(ErrorCode.SendMessageToActivity_NotJoin);
                }

                List<Data.ActivityMember> memberList = amRep.GetList(activityId);

                bool creatorIsMember = false;
                for (int index = 0; index < memberList.Count; index++)
                {
                    int targetUserId = memberList[index].Id;

                    if (targetUserId == activity.CreatorId)
                    {
                        creatorIsMember = true;
                    }

                    DateTime now = DateTime.Now;
                    string targetClipIdentityText = string.Format("{0}-{1}", activityId, targetUserId);

                    // 获取目标消息夹
                    MessageClip targetMessageClip = mcReps.Get(BasicData.MessageClipType.FriendsNotice, targetClipIdentityText);
                    if (targetMessageClip == null)
                    {
                        targetMessageClip = new MessageClip();
                        targetMessageClip.Id = Guid.NewGuid();
                        targetMessageClip.CreatedTime = now;
                        targetMessageClip.ReceiverId = targetUserId;
                        targetMessageClip.MessageCount = 1;
                        targetMessageClip.NewMessageCount = 1;
                        targetMessageClip.LastestContent = content;
                        targetMessageClip.LastestSenderId = userId;
                        targetMessageClip.LastestTitle = activity.Title;
                        targetMessageClip.LastestUpdatedTime = now;

                        targetMessageClip.Type = BasicData.MessageClipType.FriendsNotice;
                        targetMessageClip.MessageType = BasicData.MessageType.ActivityInstantMessage;
                        targetMessageClip.IdentityText = targetClipIdentityText;

                        targetMessageClip.Tag = activityId.ToString();

                        mcReps.Create(targetMessageClip);
                    }
                    else
                    {
                        targetMessageClip.MessageCount++;
                        targetMessageClip.LastestContent = content;
                        targetMessageClip.LastestSenderId = userId;
                        targetMessageClip.LastestTitle = activity.Title;
                        targetMessageClip.LastestUpdatedTime = now;
                        targetMessageClip.IsDeleted = false;
                        mcReps.Update(targetMessageClip);
                    }
                    // 创建消息
                    Message targetMessage = new Message();
                    targetMessage.Id = Guid.NewGuid();
                    targetMessage.SenderId = userId;
                    targetMessage.ReceiverId = targetUserId;
                    targetMessage.Content = content;
                    targetMessage.CreatedTime = now;
                    targetMessage.Type = BasicData.MessageType.ActivityInstantMessage;
                    targetMessage.MessageClipId = targetMessageClip.Id;
                    reps.Create(targetMessage);
                }

                if(!creatorIsMember)
                {
                    // 队长不是成员，单独给队长发送一份
                    int targetUserId = activity.CreatorId;

                    DateTime now = DateTime.Now;
                    string targetClipIdentityText = string.Format("{0}-{1}", activityId, targetUserId);

                    // 获取目标消息夹
                    MessageClip targetMessageClip = mcReps.Get(BasicData.MessageClipType.FriendsNotice, targetClipIdentityText);
                    if (targetMessageClip == null)
                    {
                        targetMessageClip = new MessageClip();
                        targetMessageClip.Id = Guid.NewGuid();
                        targetMessageClip.CreatedTime = now;
                        targetMessageClip.ReceiverId = targetUserId;
                        targetMessageClip.MessageCount = 1;
                        targetMessageClip.NewMessageCount = 1;
                        targetMessageClip.LastestContent = content;
                        targetMessageClip.LastestSenderId = userId;
                        targetMessageClip.LastestTitle = activity.Title;
                        targetMessageClip.LastestUpdatedTime = now;

                        targetMessageClip.Type = BasicData.MessageClipType.FriendsNotice;
                        targetMessageClip.MessageType = BasicData.MessageType.ActivityInstantMessage;
                        targetMessageClip.IdentityText = targetClipIdentityText;

                        targetMessageClip.Tag = activityId.ToString();

                        mcReps.Create(targetMessageClip);
                    }
                    else
                    {
                        targetMessageClip.MessageCount++;
                        targetMessageClip.LastestContent = content;
                        targetMessageClip.LastestSenderId = userId;
                        targetMessageClip.LastestTitle = activity.Title;
                        targetMessageClip.LastestUpdatedTime = now;
                        targetMessageClip.IsDeleted = false;
                        mcReps.Update(targetMessageClip);
                    }
                    // 创建消息
                    Message targetMessage = new Message();
                    targetMessage.Id = Guid.NewGuid();
                    targetMessage.SenderId = userId;
                    targetMessage.ReceiverId = targetUserId;
                    targetMessage.Content = content;
                    targetMessage.CreatedTime = now;
                    targetMessage.Type = BasicData.MessageType.ActivityInstantMessage;
                    targetMessage.MessageClipId = targetMessageClip.Id;
                    reps.Create(targetMessage);
                }

                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<string>(ErrorCode.NoError, string.Empty);
                }
                return new ServiceResult<string>(ErrorCode.DB_Error);
            }
        }

        /// <summary>
        /// 获取实时消息列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="targetUserId"></param>
        /// <returns></returns>
        public ServiceResult<List<Data.MessageView>> GetInstantMessageList(int userId, int targetUserId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                MessageRepository reps = new MessageRepository(dbContext);
                MessageClipRepository clipReps = new MessageClipRepository(dbContext);
                string clipIdentityText = string.Format("{0}-{1}", targetUserId, userId);
                MessageClip clip = clipReps.Get(BasicData.MessageClipType.FriendsNotice, clipIdentityText);
                if (clip != null)
                {
                    List<Data.MessageView> lst = reps.GetList(clip.Id);
                    // 删除这些消息
                    DeleteMessageClip(dbContext, clip.Id);

                    dbContext.SaveChanges();
                    return new ServiceResult<List<Data.MessageView>>(ErrorCode.NoError, lst);
                }
                return new ServiceResult<List<Data.MessageView>>(ErrorCode.NoError, new List<Data.MessageView>());
            }
        }

        public ServiceResult<List<Data.MessageView>> GetInstantMessageList(int userId, Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                MessageRepository reps = new MessageRepository(dbContext);
                MessageClipRepository clipReps = new MessageClipRepository(dbContext);
                string clipIdentityText = string.Format("{0}-{1}", activityId, userId);
                MessageClip clip = clipReps.Get(BasicData.MessageClipType.FriendsNotice, clipIdentityText);
                if (clip != null)
                {
                    List<Data.MessageView> lst = reps.GetList(clip.Id);
                    // 删除这些消息
                    DeleteMessageClip(dbContext, clip.Id);

                    dbContext.SaveChanges();
                    return new ServiceResult<List<Data.MessageView>>(ErrorCode.NoError, lst);
                }
                return new ServiceResult<List<Data.MessageView>>(ErrorCode.NoError, new List<Data.MessageView>());
            }
        }

        /// <summary>
        /// 删除消息夹
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="type"></param>
        /// <param name="identityText"></param>
        public void DeleteMessageClip(JzSportDbContext dbContext, int type, string identityText)
        {
            // 删除好友申请的消息
            MessageRepository msgReps = new MessageRepository(dbContext);
            MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);
            MessageClip messageClip = msgSetReps.Get(type, identityText);
            if (messageClip != null)
            {
                messageClip.IsDeleted = true;
                msgReps.DeleteByClip(messageClip.Id);
                msgSetReps.Update(messageClip);
            }
        }

        public void DeleteMessageClip2(JzSportDbContext dbContext, int type, string identityText)
        {
            MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);
            MessageClip messageClip = msgSetReps.Get(type, identityText);
            if (messageClip != null)
            {
                DeleteMessageClip(dbContext, messageClip.Id);
            }
        }
        public void DeleteMessageClip(JzSportDbContext dbContext, Guid messageClipId)
        {
            dbContext.Database.ExecuteSqlCommand("exec SP_DeleteMessageClip @id={0}", new object[] { messageClipId });
        }

        public ServiceResult<string> DeleteMessageClip(int accountId, Guid messageClipId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                DeleteMessageClip(dbContext, messageClipId);
                return new ServiceResult<string>(ErrorCode.NoError, string.Empty);
            }
        }

        public ServiceResult<string> DeleteMessage(int accountId, Guid messageId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                MessageRepository mReps = new MessageRepository(dbContext);
                Message message = mReps.Get(messageId);
                if (message != null)
                {
                    mReps.Delete(message);
                    dbContext.SaveChanges();
                }
                return new ServiceResult<string>(ErrorCode.NoError, string.Empty);
            }
        }
    }
}
